// index.js
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

Page({
  data: {
    url: 'http://www.tp6.com/index.php', 	//后台请求域名，需要修改你自己的本地或者线上域名
    //url: 'http://www.tp8.com/index.php', 	//后台请求域名，需要修改你自己的本地或者线上域名
    openid: '',
		phone: '',
    userInfo: {
      avatarUrl: defaultAvatarUrl,
      nickName: '',
    },
    hasUserInfo: false,
    canIUseGetUserProfile: wx.canIUse('getUserProfile'),
    canIUseNicknameComp: wx.canIUse('input.type.nickname'),
  },
  bindViewTap() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onChooseAvatar(e) {
    const { avatarUrl } = e.detail
    const { nickName } = this.data.userInfo
    this.setData({
      "userInfo.avatarUrl": avatarUrl,
      hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
    })
  },
  onInputChange(e) {
    const nickName = e.detail.value
    const { avatarUrl } = this.data.userInfo
    this.setData({
      "userInfo.nickName": nickName,
      hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
    })
  },
  getUserProfile(e) {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res)
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    })
  },
  wxLogin() {
    wx.login({
      success: (res) => {
        //console.log('登录成功，code为：' + res.code);
        // 获取临时登录凭证code
        wx.request({
          url: this.data.url + '/wechat/getOpenid',
          method: 'POST',
          data: {
            code: res.code
          },
          header: {},
          success: (res) => {
            //console.log(res.data);
            //this.data.openid = res.data.data;
            this.setData({
              openid: res.data.data
            })
          }
        });
      },
      fail: (err) => {
        console.error('登录失败：', err);
      }
    });
  },
  onGetPhoneNumber(e) {
    //console.log("用户信息：", e.detail);
    if (e.detail.code) {
      wx.request({
        url: this.data.url + '/wechat/getPhoneNumber',
        method: 'POST',
        data: {
          phone_code: e.detail.code
        },
        header: {},
        success: (res) => {
          //console.log(res.data);
          //this.data.phone = res.data.data;
          //console.log(this.data.phone);
          this.setData({
            phone: res.data.data
          })
        }
      });
    } else {
      console.log("用户信息：", e.detail);
    }
  },
})
